# Sampler. R          

# Provides a function to sample from posteori for mixture model

Sample_Model <- function(
                          data=data
                        , chains=2
                        , adapt = 500
                        , update.iter = 100
                        , sample.iter = 100
                        , model.file = "Model.bug"
                        , watch=c("p", "delta","beta", "diff")
                        , dic.sample = FALSE
                        ,covariates=controls[-1]
                        )
{

  require(rjags)
  
 # Get Data out of data.frame
 ###############

  # Drop missings
  data <- na.omit(data)
  data$a11 <- 0 ; data$a11[data$a1==1] <- 1 ; a11 <- data$a11
  data$a12 <- 0 ; data$a12[data$a1==2] <- 1 ; a12 <- data$a12
  
  # BUGS
  if(model.file == "func/Model_oest.bug"){
   s <- grep("rat",names(data))
 } else { # case of SPO-FPO
   s <- c("Up1","Up2","Up1")
 }

    # JAGS Data
  jags.dta <- list(
                     "N"     = nrow(data)
                   , "Y"   =  as.numeric(data$Y)
                   , "Up1" = c(data[,s[1]])
                   , "Up2" = c(data[,s[2]])
                   ,"Ucp" = c(data[,s[3]])
                   , "X"   = as.matrix(data[covariates])
                   ,"PID1" = as.numeric(data$Pid1)
                   ,"PID2" = as.numeric(data$Pid2)
                   ,"a11"= a11
                   ,"a12"= a12
                   ,"lr1"=data[,"lr1"]
                   ,"lr2"=data[,"lr2"]
                   )

  
   # Set-Up Model
   cat("Set-up Model graph \n \n ")
   jagsModel <- jags.model(model.file,
                   data = jags.dta,
                   n.chains = chains,
                   n.adapt= adapt)

  if(dic.sample==FALSE) {
  # Update 
  cat("Update Model \n\n")
  update(jagsModel, n.iter=update.iter)

  # Coda Sample
  cat("Sample Values for : ", watch, "\n")
  res <- coda.samples(jagsModel, watch, n.iter= sample.iter)


  return(res)
  
  # Get DIC
  } else {
    cat("\n DIC \n ")
    dic <- dic.samples(jagsModel, n.iter=200)
    return(dic)
    }

  }
